import { type FC, useEffect, useState } from 'react';

import {
  equipmentAccessProtocolListByNodeTypeApi,
  type SysAccessProtocol,
} from '@/api/equipmentAccessProtocolApi';
import { type ProductItem } from '@/api/equipmentProductApi';
import {
  equipmentProductCategoryListApi,
  type SysProductCategory,
} from '@/api/equipmentProductCategoryApi';
import CitySelect from '@/components/CitySelect';
import CustomUpload from '@/components/CustomUpload';
import { objToArray, ProductNodeType } from '@/constants';
import { TableLocalePresets } from '@/utils/tableUtils';

/**
 * 设备产品添加表单组件属性
 */
interface EquipmentProductAddProps {
  /** 表单实例 */
  form: FormInstance;
  /** 产品数据 */
  data: ProductItem;
  /** 是否从协议页面调用 */
  fromProtocol?: boolean;
}

const TableModal = (props: { title: string; onClose: () => void }) => {
  const { title, onClose } = props;
  // 控制弹窗显示状态
  const [visible, setVisible] = useState(true);

  // 表格列配置
  const modelColumns = [
    {
      title: '功能类型',
      dataIndex: 'funType',
      key: 'funType',
    },
    {
      title: '功能名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '标识符',
      dataIndex: 'identifier',
      key: 'identifier',
    },
    {
      title: '数据类型',
      dataIndex: 'dataType',
      key: 'dataType',
    },
  ];
  // 表格数据
  const modelData = [
    {
      funType: '属性',
      id: 1,
      name: 'SIM卡',
      identifier: 'SimCardType',
      dataType: 'STRING',
    },
    {
      funType: '属性',
      id: 2,
      name: 'SIM卡',
      identifier: 'SimCardType',
      dataType: 'STRING',
    },
  ];
  return (
    <AModal
      destroyOnHidden
      title={`${title}标准物模型定义`}
      open={visible}
      onCancel={() => {
        onClose();
        setVisible(false);
      }}
      footer={null} // 不显示底部按钮
    >
      <ATable
        columns={modelColumns}
        dataSource={modelData}
        locale={TableLocalePresets.product()}
        rowKey="id" // 使用id作为行的唯一标识
        size="middle"
        pagination={false} // 不显示分页
      />
    </AModal>
  );
};

const EquipmentProductAddForm: FC<EquipmentProductAddProps> = props => {
  const { form, fromProtocol = false } = props;
  /** 节点类型 */
  const nodeType = AForm.useWatch('nodeType', form);
  /** 产品类型 */
  const _categoryId = AForm.useWatch('categoryId', form);
  /** 接入协议列表 */
  const [accessProtocolList, setAccessProtocolList] = useState<SysAccessProtocol[]>([]);
  /** 产品类型列表 */
  const [_productCategoryList, _setProductCategoryList] = useState<SysProductCategory[]>([]);
  /** 标准物模型定义弹窗是否显示 */
  const [visible, setVisible] = useState(false);
  /** 标准物模型定义弹窗标题 */
  const [title, _setTitle] = useState('');

  /**
   * 获取产品分类列表
   */
  const fetchProductCategoryList = async () => {
    const res = await equipmentProductCategoryListApi({
      page: 1,
      pageSize: 1000,
    });
    if (res.success) {
      _setProductCategoryList(
        res.data.map(v => {
          return {
            ...v,
            label: v.categoryName,
            value: v.id,
          };
        })
      );
    }
  };
  useEffect(() => {
    fetchProductCategoryList();
  }, []);

  /** 获取接入协议列表 */
  const fetchAccessProtocolList = async (nodeType: number) => {
    const res = await equipmentAccessProtocolListByNodeTypeApi({ nodeType });
    setAccessProtocolList(
      res.data.map(v => {
        return {
          ...v,
          label: v.accessProtocolName,
          value: v.id,
        };
      })
    );
  };
  useEffect(() => {
    if (nodeType) {
      fetchAccessProtocolList(nodeType);
      form.setFieldValue('accessProtocolId', '');
    }
  }, [nodeType]);

  // 从协议页面调用时的初始化设置
  useEffect(() => {
    if (fromProtocol) {
      // 设置默认节点类型为直连设备
      form.setFieldValue('nodeType', ProductNodeType.DIRECT.value);
      // 获取直连设备的接入协议列表
      fetchAccessProtocolList(ProductNodeType.DIRECT.value);
    }
  }, [fromProtocol]);

  // 当接入协议列表更新且从协议页面调用时，自动选择"泛连接"
  useEffect(() => {
    if (fromProtocol && accessProtocolList.length > 0) {
      const fanLianJieProtocol = accessProtocolList.find(protocol => protocol.label === '泛连接'); // cspell:disable-line
      if (fanLianJieProtocol) {
        form.setFieldValue('accessProtocolId', fanLianJieProtocol.value);
      }
    }
  }, [fromProtocol, accessProtocolList]);

  // 根据fromProtocol参数过滤节点类型选项
  const getNodeTypeOptions = () => {
    const allOptions = objToArray(ProductNodeType);
    if (fromProtocol) {
      // 从协议页面调用时，排除子设备选项
      return allOptions.filter(option => option.value !== ProductNodeType.SUB_DEVICE.value);
    }
    return allOptions;
  };

  // 根据fromProtocol参数过滤接入协议选项
  const getAccessProtocolOptions = () => {
    if (fromProtocol) {
      // 从协议页面调用时，只显示"泛连接"协议
      return accessProtocolList.filter(protocol => protocol.label === '泛连接');
    }
    return accessProtocolList;
  };

  return (
    <ARow gutter={8}>
      {visible && <TableModal title={title} onClose={() => setVisible(false)} />}
      <ACol span={24}>
        <AForm.Item
          name="productName"
          label="产品名称"
          rules={[{ required: true, message: '请输入产品名称' }]}
        >
          <AInput placeholder="请输入产品名称" allowClear></AInput>
        </AForm.Item>
      </ACol>
      <ACol span={24}>
        <AForm.Item
          name="cityValue"
          label="所属省市`"
          rules={[{ required: true, message: '请输入所属省市' }]}
        >
          <CitySelect />
        </AForm.Item>
      </ACol>
      {/* <ACol span={24}>
        <ARow gutter={8}>
          <ACol span={14}>
            <AForm.Item
              name="categoryId"
              label="产品类型"
              rules={[{ required: true, message: '请选择产品类型' }]}
            >
              <ASelect
                options={productCategoryList}
                onChange={(_, option) => {
                  if (option && !Array.isArray(option) && 'label' in option) {
                    const selectedOption = option as { label: string };
                    setTitle(selectedOption.label || '');
                  }
                }}
              ></ASelect>
            </AForm.Item>
          </ACol>
          <ACol span={8} className="flex-center relative top-1">
            <AButton
              disabled={!categoryId}
              onClick={() => {
                setVisible(true);
              }}
              type="primary"
              size="middle"
            >
              查看标准物模型
            </AButton>
          </ACol>
        </ARow>
      </ACol> */}
      <ACol span={12}>
        <AForm.Item
          name="nodeType"
          label="节点类型"
          rules={[{ required: true, message: '请选择节点类型' }]}
        >
          <ASelect options={getNodeTypeOptions()}></ASelect>
        </AForm.Item>
      </ACol>
      <ACol span={12}>
        <AForm.Item
          name="accessProtocolId"
          label="接入协议"
          rules={[{ required: true, message: '请选择接入协议' }]}
        >
          <ASelect options={getAccessProtocolOptions()}></ASelect>
        </AForm.Item>
      </ACol>
      {/* <ACol span={24}>
        <AForm.Item
          name="networkMode"
          label="联网方式"
          rules={[{ required: true, message: '请选择联网方式' }]}
        >
          <ACheckbox.Group
            options={Object.values(NetworkModeType).map(item => ({
              label: item.label,
              value: item.value,
            }))}
          ></ACheckbox.Group>
        </AForm.Item>
      </ACol> */}
      <ACol span={24}>
        <AForm.Item
          name="manufacturer"
          label="产品厂商"
          rules={[{ required: false, message: '请输入产品厂商' }]}
        >
          <AInput allowClear></AInput>
        </AForm.Item>
      </ACol>
      <ACol span={24}>
        <AForm.Item
          name="productModel"
          label="产品型号"
          rules={[{ required: false, message: '请输入产品型号' }]}
        >
          <AInput allowClear></AInput>
        </AForm.Item>
      </ACol>
      {/* <ACol span={24}>
        <AForm.Item
          name="enterpriseId"
          label="所属企业ID"
          rules={[{ required: true, message: '请输入所属企业ID' }]}
        >
          <RemoteSelect
            onSelect={(e, options) => {
              form.setFieldValue('enterpriseName', options.label);
            }}
            fetchData={fetchRemoteSelectData}
          />
        </AForm.Item>
      </ACol> */}
      <ACol span={24}>
        <AForm.Item
          name="type"
          label="产品描述"
          rules={[{ required: false, message: '请输入产品描述' }]}
        >
          <AInput.TextArea allowClear rows={4}></AInput.TextArea>
        </AForm.Item>
      </ACol>
      <ACol span={24}>
        <AForm.Item
          name="thumbnailArr"
          label="产品图例"
          rules={[{ required: false, message: '请上传产品图例' }]}
        >
          <CustomUpload
            acceptTypes={['image/jpeg', 'image/png']}
            maxCount={5}
            maxSize={10}
            placeholder="支持JPG、PNG、,最多支持1个文件,文件大小不超过10MB"
          />
        </AForm.Item>
      </ACol>
    </ARow>
  );
};
export default EquipmentProductAddForm;
